import React, { useState } from 'react';
import axios from 'axios';

import './GroupDetails.css';
import '../../../assets/icons/iconfont.css';
import Icon from '../../Icon';

import EditGroupNameModal from './EditGroupNameModal';
import EditNicknameModal from './EditNicknameModal';
import AddMemberModal from './AddMemberModal';
import RemoveMemberModal from './RemoveMemberModal';

interface UserData {
  _id?: string;
  username: string;
  image: string;
  isLoggedIn: boolean;
}

interface Group {
  _id: string;
  name: string;
  members: UserData[];
  admin?: string;
  description?: string;
  qrCode?: string;
  announcement?: string;
  createdBy?: string | { _id: string; username: string; image: string };
}

interface GroupDetailsProps {
  currentUser: UserData;
  selectedGroup: Group;
  onBack: () => void;
  onGroupNameChange?: (
    groupId: string,
    newName: string,
    oldName: string
  ) => void;
  onNicknameChange?: (
    groupId: string,
    newNickname: string,
    oldNickname: string
  ) => void;
  onMemberAdded?: (groupId: string, newMembers: UserData[]) => void;
  groupNicknames?: Record<string, string>;
}

const GroupDetails: React.FC<GroupDetailsProps> = ({
  currentUser,
  selectedGroup,
  onBack,
  onGroupNameChange,
  onNicknameChange,
  onMemberAdded,
  groupNicknames = {},
}) => {
  const [doNotDisturb, setDoNotDisturb] = useState(false);
  const [pinToTop, setPinToTop] = useState(false);
  const [saveToContacts, setSaveToContacts] = useState(false);
  const [showMemberNicknames, setShowMemberNicknames] = useState(true);
  const [showEditGroupNameModal, setShowEditGroupNameModal] = useState(false);
  const [showEditNicknameModal, setShowEditNicknameModal] = useState(false);
  const [showAddMemberModal, setShowAddMemberModal] = useState(false);
  const [showRemoveMemberModal, setShowRemoveMemberModal] = useState(false);
  const [currentGroupName, setCurrentGroupName] = useState(selectedGroup.name);
  const [currentNickname, setCurrentNickname] = useState(currentUser.username);

  // 初始化群聊置顶状态
  React.useEffect(() => {
    if (selectedGroup) {
      const isPinned =
        localStorage.getItem(`pinGroup_${selectedGroup.name}`) === 'true';
      setPinToTop(isPinned);
    }
  }, [selectedGroup]);

  // 初始化群昵称状态
  React.useEffect(() => {
    if (selectedGroup && currentUser) {
      const savedNickname = localStorage.getItem(
        `groupNickname_${selectedGroup._id}_${currentUser.username}`
      );
      if (savedNickname) {
        setCurrentNickname(savedNickname);
      }
    }
  }, [selectedGroup, currentUser]);

  const handleAddMember = () => {
    setShowAddMemberModal(true);
  };

  // 添加群成员到群聊
  const handleAddMemberToGroup = async (userId: string) => {
    try {
      console.log('添加群成员请求参数:', {
        groupId: selectedGroup._id,
        memberIds: [userId],
        operatorId: currentUser._id || currentUser.username,
        currentUser: currentUser,
      });

      const response = await axios.post(
        'http://localhost:3001/ysx/groups/addMembers',
        {
          groupId: selectedGroup._id,
          memberIds: [userId],
          operatorId: currentUser._id || currentUser.username,
        }
      );

      if (response.data) {
        // 通知父组件更新群成员列表
        if (onMemberAdded) {
          onMemberAdded(selectedGroup._id, response.data.members);
        }
        console.log('群成员添加成功');
      }
    } catch (error: any) {
      console.error('添加群成员失败:', error);
      if (error.response) {
        console.error('错误详情:', error.response.data);
      }
      throw error;
    }
  };

  const handleRemoveMember = () => {
    setShowRemoveMemberModal(true);
  };

  // 处理群聊置顶切换
  const handlePinGroupToggle = () => {
    if (!selectedGroup) return;
    const newPinStatus = !pinToTop;
    setPinToTop(newPinStatus);
    localStorage.setItem(
      `pinGroup_${selectedGroup.name}`,
      newPinStatus.toString()
    );
    localStorage.setItem('pinGroup_updated', Date.now().toString());
    window.dispatchEvent(new CustomEvent('pinGroupUpdated'));
  };

  // 检查当前用户是否为群主
  const isGroupCreator = () => {
    if (!selectedGroup || !currentUser) return false;
    const creatorId =
      typeof selectedGroup.createdBy === 'string'
        ? selectedGroup.createdBy
        : selectedGroup.createdBy?._id;
    return (
      creatorId === currentUser._id ||
      selectedGroup.createdBy === currentUser.username
    );
  };

  // 移除群成员
  const handleRemoveMemberFromGroup = async (userId: string) => {
    try {
      console.log('移除群成员请求参数:', {
        groupId: selectedGroup._id,
        userId: userId,
        operatorId: currentUser._id || currentUser.username,
        currentUser: currentUser,
      });

      const response = await axios.post(
        'http://localhost:3001/ysx/groups/removeMember',
        {
          groupId: selectedGroup._id,
          userId: userId,
          operatorId: currentUser._id || currentUser.username,
        }
      );

      if (response.data) {
        // 通知父组件更新群成员列表
        if (onMemberAdded) {
          onMemberAdded(selectedGroup._id, response.data.members);
        }
        console.log('群成员移除成功');
      }
    } catch (error: any) {
      console.error('移除群成员失败:', error);
      if (error.response) {
        console.error('错误详情:', error.response.data);
      }
      throw error;
    }
  };

  const handleGroupNameEdit = () => {
    setShowEditGroupNameModal(true);
  };

  const handleGroupNameSave = async (newName: string) => {
    const oldName = currentGroupName;
    setCurrentGroupName(newName);

    // 调用父组件的回调函数
    if (onGroupNameChange) {
      onGroupNameChange(selectedGroup._id, newName, oldName);
    }

    // TODO: 这里可以添加API调用来保存群名称到服务器
    console.log('群名称已修改:', { oldName, newName });
  };

  const handleQRCode = () => {
    console.log('查看群二维码');
    // TODO: 实现查看群二维码功能
  };

  const handleGroupAnnouncement = () => {
    console.log('群公告');
    // TODO: 实现群公告功能
  };

  const handleGroupManagement = () => {
    console.log('群管理');
    // TODO: 实现群管理功能
  };

  const handleNotes = () => {
    console.log('备注');
    // TODO: 实现备注功能
  };

  const handleSearchChat = () => {
    console.log('查找聊天内容');
    // TODO: 实现查找聊天内容功能
  };

  const handleNicknameEdit = () => {
    setShowEditNicknameModal(true);
  };

  const handleNicknameSave = async (newNickname: string) => {
    const oldNickname = currentNickname;
    setCurrentNickname(newNickname);

    // 保存到localStorage
    if (selectedGroup && currentUser) {
      localStorage.setItem(
        `groupNickname_${selectedGroup._id}_${currentUser.username}`,
        newNickname
      );
    }

    // 调用父组件的回调函数
    if (onNicknameChange) {
      onNicknameChange(selectedGroup._id, newNickname, oldNickname);
    }

    console.log('群昵称已修改:', { oldNickname, newNickname });
  };

  return (
    <div className="group-details-container">
      {/* 头部 */}
      <div className="group-details-header">
        <button className="back-btn" onClick={onBack}>
          <Icon iconClass="icon-zuojiantou" size={24} />
        </button>
        <h1 className="header-title">
          聊天信息 ({selectedGroup.members.length})
        </h1>
        <button style={{ border: 'none', background: 'none' }}>
          <Icon iconClass="icon-sousuo" size={24} color="black" />
        </button>
      </div>

      {/* 群成员区域 */}
      <div className="members-section">
        <div className="members-row">
          {selectedGroup.members.map((member, index) => (
            <div key={member._id || index} className="member-avatar-container">
              <div className="member-avatar">
                {member.image ? (
                  <img src={member.image} alt={member.username} />
                ) : (
                  <div className="default-avatar">
                    {member.username.charAt(0).toUpperCase()}
                  </div>
                )}
              </div>
              <div className="member-name">
                {groupNicknames[member.username] || member.username}
              </div>
            </div>
          ))}
        </div>
        <div className="action-buttons-row">
          <button className="add-member-btn" onClick={handleAddMember}>
            <div className="add-icon">+</div>
          </button>
          {isGroupCreator() && (
            <button className="remove-member-btn" onClick={handleRemoveMember}>
              <div className="remove-icon">-</div>
            </button>
          )}
        </div>
      </div>

      {/* 群设置区域 */}
      <div className="group-settings-section">
        <div className="setting-item" onClick={handleGroupNameEdit}>
          <span className="setting-label">群聊名称</span>
          <div className="setting-value">
            <span className="setting-text">{currentGroupName}</span>
            <span className="arrow">›</span>
          </div>
        </div>

        <div className="setting-item" onClick={handleQRCode}>
          <span className="setting-label">群二维码</span>
          <div className="setting-value">
            <div className="qr-icon">📱</div>
            <span className="arrow">›</span>
          </div>
        </div>

        <div className="setting-item" onClick={handleGroupAnnouncement}>
          <span className="setting-label">群公告</span>
          <div className="setting-value">
            <span className="setting-text">未设置</span>
            <span className="arrow">›</span>
          </div>
        </div>

        <div className="setting-item" onClick={handleGroupManagement}>
          <span className="setting-label">群管理</span>
          <div className="setting-value">
            <span className="arrow">›</span>
          </div>
        </div>

        <div className="setting-item" onClick={handleNotes}>
          <span className="setting-label">备注</span>
          <div className="setting-value">
            <span className="arrow">›</span>
          </div>
        </div>
      </div>

      {/* 聊天内容和通知设置区域 */}
      <div className="chat-settings-section">
        <div className="setting-item" onClick={handleSearchChat}>
          <span className="setting-label">查找聊天内容</span>
          <div className="setting-value">
            <span className="arrow">›</span>
          </div>
        </div>

        <div className="setting-item">
          <span className="setting-label">消息免打扰</span>
          <div className="setting-value">
            <div
              className={`toggle-switch ${doNotDisturb ? 'on' : 'off'}`}
              onClick={() => setDoNotDisturb(!doNotDisturb)}
            >
              <div className="toggle-circle"></div>
            </div>
          </div>
        </div>

        <div className="setting-item">
          <span className="setting-label">置顶聊天</span>
          <div className="setting-value">
            <div
              className={`toggle-switch ${pinToTop ? 'on' : 'off'}`}
              onClick={handlePinGroupToggle}
            >
              <div className="toggle-circle"></div>
            </div>
          </div>
        </div>
      </div>

      {/* 用户特定群设置区域 */}
      <div className="user-group-settings-section">
        <div className="setting-item" onClick={handleNicknameEdit}>
          <span className="setting-label">我在本群的昵称</span>
          <div className="setting-value">
            <span className="setting-text">{currentNickname}</span>
            <span className="arrow">›</span>
          </div>
        </div>

        <div className="setting-item">
          <span className="setting-label">显示群成员昵称</span>
          <div className="setting-value">
            <div
              className={`toggle-switch ${showMemberNicknames ? 'on' : 'off'}`}
              onClick={() => setShowMemberNicknames(!showMemberNicknames)}
            >
              <div className="toggle-circle"></div>
            </div>
          </div>
        </div>
      </div>

      {/* 底部指示器 */}
      <div className="bottom-indicator"></div>

      {/* 群名称修改模态框 */}
      <EditGroupNameModal
        isOpen={showEditGroupNameModal}
        currentGroupName={currentGroupName}
        onClose={() => setShowEditGroupNameModal(false)}
        onSave={handleGroupNameSave}
      />

      {/* 昵称修改模态框 */}
      <EditNicknameModal
        isOpen={showEditNicknameModal}
        currentNickname={currentNickname}
        onClose={() => setShowEditNicknameModal(false)}
        onSave={handleNicknameSave}
      />

      {/* 添加群成员模态框 */}
      <AddMemberModal
        isOpen={showAddMemberModal}
        onClose={() => setShowAddMemberModal(false)}
        onAddMember={handleAddMemberToGroup}
        currentGroupId={selectedGroup._id}
        currentMembers={selectedGroup.members}
        currentUser={currentUser}
      />

      {/* 移除群成员模态框 */}
      <RemoveMemberModal
        isOpen={showRemoveMemberModal}
        onClose={() => setShowRemoveMemberModal(false)}
        onRemoveMember={handleRemoveMemberFromGroup}
        currentGroupId={selectedGroup._id}
        currentMembers={selectedGroup.members}
        currentUser={currentUser}
        groupCreator={
          typeof selectedGroup.createdBy === 'string'
            ? selectedGroup.createdBy
            : selectedGroup.createdBy?._id || ''
        }
      />
    </div>
  );
};

export default GroupDetails;
